import React, { useState, useEffect, useRef } from 'react'
import { View, Text } from '@tarojs/components'
import Header from '@/pages/messageApp/component/header'
import Taro from '@tarojs/taro'
import { LgTabs, LgTab } from '../../components/tabs'
import { HttpPut, HttpGet } from '../../../network/servers'
import Empty from '../../components/emptyContent'
import { connect } from 'react-redux'
import { AtSwitch } from 'taro-ui'
import Utils from '../../../utils'
import { Switch } from 'antd-mobile'
import './index.scss'
import { stubTrue } from 'lodash'
import { useDocumentTitle } from '@/utils/myUtils'

const {
    getNowToken
} = Utils


function App(props) {

    const {
        userInfo,
        isEdu
    } = props

    useDocumentTitle('消息中心设置',false)

    const token = getNowToken()
    const [currentIndex, setCurrentIndex] = useState('sysReceive')
    const [messageSettingList, setMessageSettingList] = useState([])
    const [shieldSettingList, setShieldSettingList] = useState([])
    const [publicInfoAddr, setPublicInfoAddr] = useState('')
    const [shieldCount, setShieldCount] = useState(0)

    const choTab = (value) => {
        if (value == 1) {
            setCurrentIndex('onlineChat')
        } else {
            setCurrentIndex('sysReceive')
        }
    }

    // 获取系统消息屏蔽设置列表
    const getMesSettingInfo = async () => {
        const { UserID, UserType, SchoolID } = userInfo
        HttpGet({
            url: '/api/setting/list/getPageList',
            data: {
                schoolId: SchoolID,
                userId: UserID,
                userType: UserType,
                schoolLevel: userInfo.SchoolLevel || '2',
                environment: isEdu?1:2
            },
            load: true
        }).then((result) => {
            if (result.code == 200) {
                let arr = JSON.parse(JSON.stringify(result.data.msgTypeList))
                // 计算得出
                arr && arr.forEach(item => {
                    let flags = item.templateList.some(child => {
                        return child.isPush == 0
                    });

                    if (flags) {
                        item.checked = true
                    } else {
                        item.checked = false
                    }
                });

                setMessageSettingList(arr)
                Taro.hideLoading()
            }
        })


    }

    // console.log(levelOneChecked);

    // 获取在线交流屏蔽列表
    const getShieldSetting = async () => {
        const { UserID, UserType, SchoolID } = userInfo
        let url = ''
        Taro.getSysWeb({ sysId: '400' }, 'web', function (data) {
            url = data + '/Chat/GetShieldList'
            HttpGet({
                url,
                data: {
                    UserClass: 0,
                    SchoolID,
                    UserID,
                    UserType,
                    Token: token,
                    SecretKey: '',
                    BackUpOne: '',
                    BackUpTwo: '',
                    URL: url,
                },
                header: {
                    Authorization: ' X-Token=' + getNowToken()
                },
                load:true,
                showError:false
            }).then((result) => {
                if (result.StatusCode == 200) {
                    setShieldSettingList(result.Data.UserList)
                    setShieldCount(result?.Data?.UserList?.length || 0)
                    Taro.hideLoading()
                }
            })
        })
    }

    // 总开关
    const handleSwitch = (data, value) => {
        const { UserID, UserType, SchoolID } = userInfo
        let list = [] as any;
        Array.isArray(data.templateList) &&
            data.templateList.forEach((child) => {
                list.push({
                    templateId: child.templateId,
                    isPush: value ? 1 : 0
                });

            })
        HttpPut({
            url: "/api/setting/manage/batch/shield",
            data: {
                schoolId: SchoolID,
                userId: UserID,
                isPushList: list
            },
        }).then((result) => {
            let info = JSON.parse(JSON.stringify(messageSettingList));
            info.forEach((item) => {
                if (item.msgTypeId === data.msgTypeId) {
                    item.checked = value
                    item.templateList.forEach((child) => {
                        child.isPush = value ? 0 : 1;
                    })
                }
            })

            setMessageSettingList(info)
        })
    }

    // 二级开关事件
    const handleLevelTwo = (data, value, father) => {
        const { UserID, UserType, SchoolID } = userInfo

        HttpPut({

            url: '/api/setting/manage/batch/shield',
            data: {
                schoolId: SchoolID,
                userId: UserID,
                isPushList: [{
                    templateId: data.templateId,
                    isPush: value ? 1 : 0,
                }],
            },
        }).then((result) => {
            let info = JSON.parse(JSON.stringify(messageSettingList))
            info.forEach(item => {
                if (item.msgTypeId == father.msgTypeId) {
                    item.templateList.forEach(i => {
                        if (i.templateId == data.templateId) {
                            i.isPush = value ? 0 : 1
                        }
                    });
                }
            });

            info.forEach(item => {

                if (item.msgTypeId == father.msgTypeId) {

                    let flag = item.templateList.some(child => {
                        return child.isPush == 0
                    })
                    item.checked = flag
                }
            });
            setMessageSettingList(info)
        })
    }

    // 移除屏蔽人
    const removeShield = (item) => {
        const { UserID, UserType, SchoolID } = userInfo
        Taro.getSysWeb({ sysId: '400' }, 'web', function (data) {
            let url = data + '/Chat/CancelShieldUser'
            HttpGet({
                url,
                data: {
                    SenderID: UserID,
                    CancelShieldUserID: item.UserID,
                    URL: publicInfoAddr,
                    SchoolID,
                    UserID,
                    UserType,
                    Token: getNowToken(),
                    SecretKey: '',
                    BackUpOne: '',
                    BackUpTwo: ''
                },
                header: {
                    Authorization: 'X-Token=' + getNowToken()
                }
            }).then((result) => {
                if (result.StatusCode == 200) {
                    getShieldSetting()
                }
            })
        })

    }

    useEffect(() => {
        if (currentIndex == 'sysReceive') {
            getMesSettingInfo()
        } else {
            getShieldSetting()
        }
    }, [currentIndex])


    return (
        <View className='set_container'>
            <Header
                title='消息中心设置'
                isBlod={false}
                isLeft={true}
            />
            <View className='tbs_container-a'>
                {/* <LgTabs onClick={choTab} unifiedAllocation>
                    <LgTab title='系统接收消息设置'>
                    </LgTab>
                    <LgTab title='在线交流屏蔽名单'>
                    </LgTab>
                </LgTabs> */}
            </View>
            {
                currentIndex == 'onlineChat' ?
                    <View className='shield_body'>
                        <View className='shield_count'>
                            <Text>共</Text>
                            <Text className='text'>{shieldCount}</Text>
                            <Text>人</Text>
                        </View>
                        <View className='shield_list'>
                            {
                                shieldSettingList.length > 0 ?
                                    shieldSettingList.map((item: any, index) => {
                                        let avatarUrl=item.PhotoPath?`url(${item.PhotoPath})`:''
                                        return (
                                            <View className='shield_one'>
                                                <View className='left'>
                                                <View
                                                    className='avatar'
                                                    style={{
                                                        backgroundImage:avatarUrl
                                                    }}
                                                ></View>
                                                    <View className='name'>{decodeURIComponent(item.UserName)}</View>
                                                    <View className='id'>({item.UserID})</View>
                                                </View>
                                                <View className='right' onClick={() => removeShield(item)}>移除</View>
                                            </View>
                                        )
                                    }) :
                                    <View style={{ height: '60vh' }}>
                                        <Empty type='B' text='暂无屏蔽人' />
                                    </View>
                            }
                        </View>
                    </View> :

                    <View className='set_body'>
                        <View className='sys'>
                            {
                                messageSettingList.length > 0 ?
                                    messageSettingList.map((item: any, index) => {
                                        return (
                                            <View className='level_one' key={index}>
                                                <View className='header'>
                                                    <Text className='one_title'>{item.msgTypeDescription}</Text>
                                                    <Switch
                                                        checked={item['checked']}
                                                        onChange={(value) => { handleSwitch(item, value) }}
                                                        style={{
                                                            '--width': '47px',
                                                            '--height': '28px',
                                                            '--checked-color': '#4bd763'
                                                        }}
                                                    />
                                                </View>
                                                <View className='body'>
                                                    {
                                                        item.templateList.length > 0 ?
                                                            item.templateList.map((child, i) => {
                                                                return (
                                                                    <View className='level_two' key={i}>
                                                                        <Text className='title'>{child.templateDescription}</Text>
                                                                        <Switch
                                                                            checked={child.isPush == 0 ? true : false}
                                                                            onChange={(value) => { handleLevelTwo(child, value, item) }}
                                                                            style={{
                                                                                '--width': '36px',
                                                                                '--height': '21px',
                                                                                '--checked-color': '#4bd763'
                                                                            }}
                                                                        />
                                                                    </View>
                                                                )
                                                            }) : ''
                                                    }
                                                </View>
                                            </View>
                                        )
                                    }) : ''
                            }
                        </View>
                    </View>
            }

        </View>
    )
}


const mainProps = ({ commonData }) => {
    return {
        userInfo: commonData.userInfo,
        isEdu:commonData.isEdu
    }
}

export default connect(mainProps)(App)